package cn.ccccltd.waf.message.email.consumer;

import java.util.Map;

import javax.annotation.Resource;
import javax.jms.Message;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

import cn.ccccltd.waf.message.base.consumer.BaseErrorConsumer;
import cn.ccccltd.waf.message.constant.MessageConstants;
import cn.ccccltd.waf.message.email.constant.EmailConstants;
import cn.ccccltd.waf.message.init.PropertyContext;
import cn.ccccltd.waf.message.model.vo.MessageEmail;
import cn.ccccltd.waf.message.queue.error.constant.ErrorConstants;
import cn.ccccltd.waf.message.queue.log.util.LogMessageUtils;
import cn.ccccltd.waf.message.util.JsonUtils;
import cn.ccccltd.waf.message.util.sql.SqlContext;
import cn.ccccltd.waf.message.util.sql.SqlTools;

/**
 * 创建日期:2017年11月14日
 * Title: 发送邮件失败重试消费者
 * Description：对本文件的详细描述，原则上不能少于50字
 * @author yangjingjiang
 * @mender：（文件的修改者，文件创建者之外的人）
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@Component("errorEmailConsumer")
public class ErrorEmailConsumer extends BaseErrorConsumer{

	
	@Resource(name="emailUpdateTableJmsTemplate")
	private JmsTemplate emailUpdateTableJmsTemplate;
	
	@Autowired
	private JavaMailSender mailSender;
	
	@Override
	@JmsListener(destination=ErrorConstants.ERROR_QUEUE, selector = MessageConstants.SELECTOR + "='"+EmailConstants.EMAIL_ERROR_MESSAGE_SELECTOR+"'", containerFactory="jmsListenerContainerFactory" )
	public void receiveMessage(Message message) {
		
		super.receiveMessage(message);
		
	}

	@Override
	protected SqlContext getUpdateSqlContext(JSONObject emailMessage) {
		
		MessageEmail email = JsonUtils.toObject(emailMessage.toJSONString(), MessageEmail.class);
		SqlContext updateContext = SqlTools.getUpdate(email);
		
		return updateContext;
	}

	@Override
	protected JmsTemplate getUpdateTableJmsTemplate() {
		
		return emailUpdateTableJmsTemplate;
		
	}

	@Override
	protected Map<String, String> sendMessage(JSONObject emailMessage) {
		
		String code = "200";
		String message = "邮件发送成功！";
		
		/**
		 * 具体的发送消息的
		 */
		final SimpleMailMessage smm = new SimpleMailMessage();
		String from = PropertyContext.getProperty("mail.default.from");
		smm.setFrom(from);
		smm.setTo(emailMessage.getString("emailAddress"));
		smm.setSubject(emailMessage.getString("msgTopic"));
		smm.setText(emailMessage.getString("content"));

		try {
			mailSender.send(smm);
		} catch (MailException e) {
			code = "500";
			message = e.getLocalizedMessage();
			e.printStackTrace();
		}
		
		/**
		 * smsMessage.getString("emailId") 邮箱等真实表的id
		 */
		return LogMessageUtils.getSendLogMap(emailMessage.getString("emailId"), code, message);
	}
	
	
}
